# _*_ coding:utf-8 _*_
# @Time  : 2022.12.08
# @Author: zizlee

__all__ = ['investment_plan_api']

from fastapi import APIRouter, Header, Query

from global_constant import VARIETY
from hutool import security
from db import FAConnection
from v1_all_api.all_response import AllResponse

investment_plan_api = APIRouter()


@investment_plan_api.get('/')   # 根据对外用户角色查询投资方案
def query_investment(ruizy_token: str = Header(...), page: int = Query(1), page_size: int = Query(10),
                     v: str = Query('')):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()

    # 查询用户信息
    with FAConnection() as cursor:
        cursor.execute('SELECT id,out_role,is_proponent FROM ruizy_user WHERE id=%s LIMIT 1;', [person['uid']])
        user = cursor.fetchone()
    if not user:
        return AllResponse.no_authorization()

    # 1: '展示', 2: '实盘', 3: '外发'
    # 投资经理：实盘
    # 咨询人员: 外发
    # 研究人员: 自己

    sql = """
        SELECT id,create_time,active_date,expire_date,title,category,varieties,filepath
        FROM exchange_plan 
    """
    prm = []
    if person.get('out_role', -1) == 0:  # 没分配身份的不能看
        return AllResponse.operate_successfully(data={
            'data': [],
            'total_count': 0,
            'total_page': 0,
            'page': 0
        })
    # 投资经理看有咨询证人员发的，且审核通过为实盘的examine_ret=2  # a.creator in (SELECT id FROM ruizy_user WHERE is_proponent=1)有咨询证的人
    if user['out_role'] == 254:  # 投资经理
        sql += 'WHERE is_outer=1 AND examine_ret=2 AND is_delete=0 '
    elif user['out_role'] == 255:  # 最高级管理人员看全部
        sql += 'WHERE is_delete=0 '
    else:  # 其他只看自己   251:  # 研究员人员看自己
        sql += 'WHERE examine_ret>0 AND is_delete=0 AND creator=%s '
        prm.append(person['uid'])

    # # 其他人员不得看
    # elif person.get('out_role', -1) == 254:  # 投资经理看实盘
    #     sql += 'WHERE examine_ret=2 AND is_delete=0 '
    # elif person.get('out_role', -1) == 253:  # 咨询人员看外发
    #     sql += 'WHERE examine_ret=3 AND is_delete=0 '
    # elif person.get('out_role', -1) == 252:  # 内部其他人员看内部展示
    #     sql += 'WHERE examine_ret=1 AND is_delete=0 '
    # elif person.get('out_role', -1) == 251:  # 研究人员看自己
    #     sql += 'WHERE examine_ret>0 AND is_delete=0 AND creator=%s '
    #     prm.append(person['uid'])
    # else:  # 其他只剩255， 看全部
    #     sql += 'WHERE is_delete=0 '

    # 2023.07.01之后的记录需要过滤掉公募人员


    if v:
        sql += 'AND FIND_IN_SET(varieties, %s) '
        prm.append(v)
    sql += 'ORDER BY create_time DESC;'
    db = FAConnection()
    ret = db.query_paginator(sql, prm, page=page, page_size=page_size)
    for item in ret['data']:
        item['create_time'] = item['create_time'].strftime('%Y-%m-%d %H:%M:%S')
        item['active_date'] = item['active_date'].strftime('%Y-%m-%d')
        item['expire_date'] = item['expire_date'].strftime('%Y-%m-%d')
        item['variety'] = ','.join([VARIETY.VARIETY_NAMES.get(i, i) for i in item['varieties'].split(',')])
    return AllResponse.operate_successfully(data=ret)
